package no.saiboten.tourbuilder.tournament.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import no.saiboten.tourbuilder.tournament.Tournament;
import no.saiboten.tourbuilder.tournament.TournamentSize;
import no.saiboten.tourbuilder.tournament.service.TournamentService;
import no.saiboten.tourbuilder.user.User;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class TournamentServiceMock implements TournamentService {

	@Resource
	Map<String, Tournament> tournaments;

	final Logger LOGGER = Logger.getLogger(getClass());

	@Override
	public void createTournament(String name, Date startTime, Date endTime,
			TournamentSize size) {
		Tournament tournament = new Tournament();
		tournament.setId(name);
		tournament.setStartdate(startTime);
		tournament.setEndDate(endTime);
		tournament.setTournamentSize(size);
		tournaments.put(name, tournament);
	}

	@Override
	public Map<String, Tournament> findAllTournaments() {
		return tournaments;
	}

	@Override
	public Tournament getTournament(String tournamentId) {
		return tournaments.get(tournamentId);
	}

	@Override
	public Map<String, Tournament> findAllTournamentsOnGivenDay(Date day) {

		Map<String, Tournament> result = new HashMap<String, Tournament>();
		for (Tournament tournament : tournaments.values()) {
			Calendar inputDate = Calendar.getInstance();
			inputDate.setTime(day);

			Calendar tournamentDate = Calendar.getInstance();
			inputDate.setTime(tournament.getStartdate());

			if (inputDate.get(Calendar.YEAR) == tournamentDate
					.get(Calendar.YEAR)
					&& inputDate.get(Calendar.DAY_OF_YEAR) == tournamentDate
							.get(Calendar.DAY_OF_YEAR)) {
				result.put(tournament.getId(), tournament);
			}
		}
		return result;
	}

	@Override
	public boolean addUserToTournament(User user, String tournamentStr) {
		for (Tournament tournament : tournaments.values()) {
			if (tournament.getId().equals(tournamentStr)) {
				if (tournament.getUsers().size() + 1 <= tournament
						.getTournamentSize().getSize()) {
					tournament.addUser(user);
					return true;
				} else {
					LOGGER.debug("Tournament full!");
				}
			}
		}
		return false;
	}

	@Override
	public boolean deleteTournament(String tournamentId) {
		if (tournaments.containsKey(tournamentId)) {
			tournaments.remove(tournamentId);
			return true;
		}
		return false;
	}

}
